-- 账户数据库
-- Author: Colocaisa
-- Date: 2019-05-17
local log = require "log";
local md5 =	require	"md5";

local db_account = {}

local redis_prefix = 'account:'
local valid_time = 86400;

function db_account:init(get_func)
    local t = self:query("SELECT * FROM account;");
    -- log.dump(t);
    -- self:account_insert("pig11", "222222");
    
    -- local acc = self:hgetall('account:10000001');
    -- log.dump(acc, "acc");
    
    local pr = self:account_select(2);
    log.dump(pr, "pr");

    local rr = self:hgetall('account:2');
    log.dump(rr, "rr");
end

---id查找账号
---@param acc_id string
---@return table
function db_account:find_account(acc_id)
    -- print("find_account", acc_id);
    local key = redis_prefix..acc_id;
    local result = self:hgetall(key);
    if not result then
        result = self:account_select(acc_id);
    end

    self:expire_account(result);
    result = result and result[1];
    -- log.dump(result, "find_account");
    return result;
end

-- 用户名查找账号
function db_account:find_account_by_name(acc_name)
    -- print("find_account_by_name", acc_name);
    local key = redis_prefix.."name_"..acc_name;
    local result = self:hgetall(key);
    if not result then
        result = self:account_select_by_name(acc_name);
    end

    self:expire_account(result);
    result = result and result[1];
    -- log.dump(result, "find_account_by_name");
    return result;
end

-- 用GUID查找账号
function db_account:find_account_by_guid(acc_guid)
    -- print("find_account_by_guid", acc_name);
    local key = redis_prefix.."guid_"..acc_guid;
    local result = self:hgetall(key);
    if not result then
        result = self:account_select_by_guid(acc_guid);
    end

    self:expire_account(result);
    result = result and result[1];
    -- log.dump(result, "find_account_by_guid");
    return result;
end

-- 设置缓存有效期
function db_account:expire_account(result)
    if not result then return end
    for _, acc in pairs(result) do
        local acc_id = acc.id
        local acc_name = acc.name
        local acc_guid = acc.guid
        self:expire(redis_prefix..acc_id, valid_time);
        self:expire(redis_prefix.."name_"..acc_name, valid_time);
        self:expire(redis_prefix.."guid_"..acc_guid, valid_time);
    end
end

-- 注册账号
function db_account:register_account(acc_name, acc_pwd)
    -- 注册账号
    local md5_pwd = md5.sumhexa(acc_pwd..acc_name);
    print('account_insert', acc_name, md5_pwd);
    local result = self:account_insert(acc_name, md5_pwd);
    log.dump(result, "register_account");
    print(type(result.code));
    return result[1] or result;
end

return db_account
